// ================================================================================
// 		File: PartyJoinLinkExample.cs
// 		Desc: 
//  
// 		Called by:   
//               
// 		Auth: chenwenzhi（--）
// 		Date: 2015-12-28 23:59
// ================================================================================
// 		Change History
// ================================================================================
// 		Date:		Author:				Description:
// 		--------	--------			-------------------
//    
// ================================================================================
// --
// ================================================================================
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using ZHDJ.Data.BLL;

namespace ZHDJ.Data.Models.JoinParty
{
    /// <summary>
    /// 
    /// </summary>   
    public class PartyJoinLinkExample
    {
        #region 属性

        [Key]
        public string StandID { get; set; }

        /// <summary>
        /// SwornID
        /// </summary>
        [StringLength(128)]
        public string SwornID { get; set; }

        /// <summary>
        /// AppllicationID
        /// </summary>
        [StringLength(128)]
        public string AppllicationID { get; set; }

        /// <summary>
        /// MeetingID
        /// </summary>
        [StringLength(128)]
        public string MeetingID { get; set; }

        /// <summary>
        /// HelperInfoID
        /// </summary>
        [StringLength(128)]
        public string HelperInfoID { get; set; }

        /// <summary>
        /// CurrentStepID
        /// </summary>
        [StringLength(128)]
        public string CurrentStepID { get; set; }

        /// <summary>
        /// CurrentStepName
        /// </summary>
        [StringLength(128)]
        public string CurrentStepName { get; set; }

        /// <summary>
        /// PreStepID
        /// </summary>
        [StringLength(128)]
        public string PreStepID { get; set; }

        /// <summary>
        /// PreStepName
        /// </summary>
        [StringLength(128)]
        public string PreStepName { get; set; }

        /// <summary>
        /// ToDoHandleUserID
        /// </summary>
        [StringLength(128)]
        public string ToDoHandleUserID { get; set; }

        /// <summary>
        /// ToDoHandleUserName
        /// </summary>
        [StringLength(128)]
        public string ToDoHandleUserName { get; set; }

        /// <summary>
        /// HandleUserID
        /// </summary>
        [StringLength(128)]
        public string HandleUserID { get; set; }

        /// <summary>
        /// HandleUserName
        /// </summary>
        [StringLength(128)]
        public string HandleUserName { get; set; }

        /// <summary>
        /// HandleTime
        /// </summary>
        public DateTime? HandleTime { get; set; }

        /// <summary>
        /// Remark
        /// </summary>
        public string Remark { get; set; }

        /// <summary>
        /// Remark
        /// </summary>
        public string Remark2 { get; set; }

        /// <summary>
        /// Status
        /// </summary>
        public int Status { get; set; }

        /// <summary>
        /// IsEffective
        /// </summary>
        public bool IsEffective { get; set; }

        /// <summary>
        /// Agree
        /// </summary>
        public int Agree { get; set; }

        /// <summary>
        /// NotAgree
        /// </summary>
        public int NotAgree { get; set; }

        /// <summary>
        /// Waiver
        /// </summary>
        public int Waiver { get; set; }

        /// <summary>
        /// OrderNo
        /// </summary>
        public int OrderNo { get; set; }

        /// <summary>
        /// CreateTime
        /// </summary>
        public DateTime? CreateTime { get; set; }

        #endregion

        #region 规则判断
        /// <summary>
        /// 详细规则判断
        /// </summary>
        /// <param name="omodel"></param>
        /// <param name="ShouldBeTo">应到人数</param>
        /// <param name="IsTo">实到人数</param>
        /// <param name="Agree">同意人数</param>
        /// <param name="Waiver">弃权人数</param>
        /// <param name="DisAgree">不同意人数</param>
        /// <returns></returns>
        public static bool CheckRule(int Agree, int Waiver, int DisAgree, int ShouldBeTo, int IsTo, out string errMsg, string only = "", string state = "0")
        {
            bool isResult = false;
            errMsg = "";

            if (ShouldBeTo != (Agree + Waiver + DisAgree))
            {
                errMsg = "数据填写有误，请检查！";
            }

            if (!string.IsNullOrEmpty(only))
            {
                if (IsTo > ShouldBeTo)
                { errMsg = "数据填写有误，实际出席人数不能大于应出席人数！"; }
                else isResult = true;
            }
            else
            {
                //规则：实到会有表决权的党员必须超过应到会有表决权的党员人数的半数
                //同意转正的有表决权的党员人数必须超过应到会有表决权的党员人数的半数方可通过；

                int temp = 0;
                if (IsTo > ShouldBeTo)
                { errMsg = "数据填写有误，实际出席人数不能大于应出席人数！"; }
                //实到超过应到半数以上
                else if ((temp = (ShouldBeTo % 2 == 0 ? (ShouldBeTo / 2) + 1 : (ShouldBeTo + 1) / 2)) > IsTo)
                { errMsg = "数据填写有误，实际出席人数必须超过应出席人数的半数！"; }
                else if (Agree > IsTo)
                { errMsg = "数据填写有误，同意人数不能大于实际出席人数！"; }
                else if (Waiver > IsTo)
                { errMsg = "数据填写有误，弃权人数不能大于实际出席人数！"; }
                else if (DisAgree > IsTo)
                { errMsg = "数据填写有误，不同意人数不能大于实际出席人数！"; }
                //同意人数+弃权人数+不同意必需等于实际出席人数
                else if (Agree + Waiver + DisAgree != IsTo)
                { errMsg = "数据填写有误，同意人数+弃权人数+不同意人数必须等于实际出席人数！"; }
                //同意人数不小于应到会人数的半数，状态不能为通过
                else if (Agree < (temp = (ShouldBeTo % 2 == 0 ? ShouldBeTo / 2 + 1 : (ShouldBeTo + 1) / 2)) && state == "0")
                { errMsg = "数据填写有误，同意人数不超过应出席人数的半数【状态】不能为【通过】！"; }
                //同意人数大于应到会人数的半数，状态只能为通过
                else if (Agree >= (temp = (ShouldBeTo % 2 == 0 ? ShouldBeTo / 2 + 1 : (ShouldBeTo + 1) / 2)) && state != "0")
                { errMsg = "数据填写有误，同意人数超过应出席人数的半数【状态】必须为【通过】！"; }
                else isResult = true;
            }
            return isResult;
        }
        #endregion

        /// <summary>
        /// 根据申请ID和指定步骤ID获取备注
        /// </summary>
        /// <param name="AppllicationID"></param>
        /// <param name="StepID"></param>
        /// <returns></returns>
        public static string GetRemark(string AppllicationID, string StepID)
        {
            StringBuilder sbsql = new StringBuilder();
            sbsql.AppendFormat(@"select * from tblPartyJoinLinkExample
                                where AppllicationID='{0}' and CurrentStepID='{1}'", AppllicationID, StepID);

            DataSet ds = MySqlHelper.ExecuteDataSet(sbsql.ToString());
            if (ds.Tables[0].Rows.Count > 0)
            {
                return ds.Tables[0].Rows[0]["Remark"].ToString();
            }
            else return "";
        }

        #region 撤回上一步骤
        /// <summary>
        /// 撤回上一步骤
        /// </summary>
        /// <param name="StandID"></param>
        /// <param name="AppllicationID"></param>
        public static void ReLastStep(string StandID, string AppllicationID, out string TipMessage, string currentLoginID = "")
        {

            TipMessage = "";
            //当前环节是否最新环节
            StringBuilder sbSql = new StringBuilder();
            sbSql.AppendFormat(@"select StandID from tblPartyJoinLinkExample 
                                where  AppllicationID ='{0}'
                                order by OrderNo desc  limit 1", AppllicationID);
            string TopStandID = Convert.ToString(MySqlHelper.ExecuteScalar(sbSql.ToString()));
            //当前环节是最新环节
            if (TopStandID == StandID)
            {
                sbSql = new StringBuilder();
                sbSql.AppendFormat(@" delete from tblPartyJoinLinkExample where StandID='{0}';
                                    delete from tblPartyJoinChildFlow where StandID='{0}';

                                    update tblPartyJoinLinkExample set Status='0' where StandID in( select *from (
                                    select  StandID from tblPartyJoinLinkExample 
                                    where  AppllicationID ='{1}'
                                    order by OrderNo desc  limit 1) as t);

                                    select StandID from tblPartyJoinLinkExample 
                                    where  AppllicationID ='{1}'
                                    order by OrderNo desc  limit 1;", StandID, AppllicationID);

                string UPStandID = Convert.ToString(MySqlHelper.ExecuteScalar(sbSql.ToString()));

                ////清除待办
                PartyTaskHelper.TaskDone(StandID, currentLoginID);
                ////还原上一步待办
                PartyTaskHelper.ReductionTaskDone(UPStandID, currentLoginID);

                TipMessage = "撤消成功！";
            }
            else
            {
                TipMessage = "撤消失败，该流程已被审核！";
            }
        }
        #endregion

        /// <summary>
        /// 公示
        /// </summary>
        /// <param name="standID"></param>
        /// <param name="appllicationID"></param>
        /// <param name="loginID"></param>
        /// <param name="stepID"></param>
        /// <param name="category"></param>
        //public static void publicity(string standID, string appllicationID, string loginID, string stepID, string category,string Title)
        //{
        //    StringBuilder sbSql = new StringBuilder();
        //    sbSql.AppendFormat(" insert into tblpartyjoinpublicity(ID,LoginID,StandID,appllicationID,StepID,Category,CreateTime,Title) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')",
        //        Core.Util.StringHelper.NewID, loginID, standID, appllicationID, stepID, category,DateTime.Now, Title);
        //    MySqlHelper.ExecuteScalar(sbSql.ToString());
        //}
        /// <summary>
        /// 获取GetDataGrid数据源
        /// </summary>
        /// <returns></returns>
        public static DataSet GetToDoFLow(string userName, string BranchID, string loginID)
        {
            var para = new List<MySqlParameter>
            {
                new MySqlParameter()
                {
                    DbType = DbType.String,
                    ParameterName = "LoginID",
                    Value = string.Format(",{0},", loginID)
                }
            };

            StringBuilder sbSql = new StringBuilder();
            sbSql.Append(@"select * from (
                            SELECT data.AppllicationID ,data.LoginID,pom.UserName,data.CreateTime,
                            (case pom.Gender when 1 then '男' when 2 then '女' else '' end) as Gender,
                            pom.IdentityCard,pom.Nation,pom.NativePlace,pom.Educational,pom.MobileNo,
                            pob.BranchID,pob.BranchName,fStance.ToDoHandleUserID,
                            fStance.CurrentStepID,fStance.CurrentStepName,fStance.StandID 
                            from tblPartyJoinApplycation data
                            inner join tblPartyJoinLinkExample fStance on data.AppllicationID=fStance.AppllicationID
                            left join tblpartyorgmember as pom on data.LoginID=pom.LoginID
                            left join tblpartyorgbranch as pob on data.BranchID=pob.BranchID
                            where fStance.Status=0)t1 where 1=1   ");

            sbSql.Append(@" and (locate(?LoginID,','+ToDoHandleUserID+',')>0 or
                                    standID in(select standID from tblPartyJoinChildFlow 
                                    where Status=0 and locate(?LoginID,','+ToDoHandleUserID+',')>0)) 
                                    ");
            if (!string.IsNullOrEmpty(userName))
            {
                sbSql.Append(string.Format(" and UserName like ?UserName", userName.Trim()));
                para.Add(
                    new MySqlParameter()
                    {
                        DbType = DbType.String,
                        ParameterName = "UserName",
                        Value = userName
                    }
                  );
            }

            sbSql.Append(" order by BranchName,CurrentStepID,CreateTime desc");
            return MySqlHelper.ExecuteDataSet(sbSql.ToString(), para.ToArray());
        }

        /// <summary>
        /// 获取数据源
        /// </summary>
        /// <param name="AppllicationID">申请ID</param>
        /// <returns></returns>
        public static DataSet GetGridData(string AppllicationID)
        {
            StringBuilder sbSql = new StringBuilder();
            sbSql.AppendFormat(@"select pj.*,po.BranchID,po.BranchName from tblPartyJoinLinkExample pj 
                                left join tblPartyOrgMember pm on pj.HandleUserID=pm.LoginID
                                left join tblPartyOrgBranch po on pm.BranchID = po.BranchID
                               where pj.AppllicationID='{0}'", AppllicationID);
            sbSql.Append(" order by pj.orderNo asc");
            return MySqlHelper.ExecuteDataSet(sbSql.ToString());
        }
    }




}

